using System;
using System.Data;
using System.Data.Common;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MagnoliaTableAdapters;
using System.Data.SqlClient;


public partial class StringTag : System.Web.UI.Page
{
    static Magnolia.STRINGTAGDataTable stringTags = new Magnolia.STRINGTAGDataTable();
    static STRINGTAGTableAdapter tagsAdapter = new STRINGTAGTableAdapter();
    static ArrayList tmpDelRuleLists = new ArrayList();
    static bool enableButton;
    static bool plusRule;
    static bool minusRule;
    static int indexCounter;
    static int oldCounter;
    static int emptyCounter;

    // global drop-down lists for all ticker editors
    static Magnolia.FONTDataTable FontList = new FONTTableAdapter().GetFonts();
    static Magnolia.COLORFONTDataTable ColorList = new COLORFONTTableAdapter().GetColorFonts();
    static Magnolia.IMAGETAGDataTable ImageTagList = new IMAGETAGTableAdapter().GetData();
    static Magnolia.DATATAGDataTable DataTagList = new DATATAGTableAdapter().GetDataTagsEnabledAndOrderedByName();

    protected void Page_Load(object sender, EventArgs e)
    {
        Page.Title = ConfigurationManager.AppSettings["PageTitle"] + " - String Tags";

        //Hide those controler from user
        hidden_CheckBox.Style.Add("display", "none");
        hidden_TextBox.Style.Add("display", "none");
        hidden_ContentSave.Style.Add("display", "none");

        // hide edit and new buttons for user access
        Btn_EditTag.Style.Add("display", "none");
        Btn_NewTag.Style.Add("display", "none");

        // format default string textarea
        Text_DefaultStringValue.Style.Add("overflow", "visible");

        // get user access permissions
        DataTable UserAccessDT = (DataTable)Session["UserAccess"];
        foreach (DataRow dr in UserAccessDT.Rows)
        {
            // edit string tag
            if (Convert.ToString(dr.ItemArray[0]) == "325")
            {
                Btn_EditTag.Style.Add("display", "block");
            }
            // new string tag
            if (Convert.ToString(dr.ItemArray[0]) == "425")
            {
                Btn_NewTag.Style.Add("display", "block");
            }
        }

        if (!Page.IsPostBack)
        {
            //Fill up the datatable
            tagsAdapter.Fill(stringTags);
            LoadList(1);
            enableButton = false;

            //Fill the default ticker editor drop downs
            DefaultTicker_FontSelect.DataSource = FontList;
            DefaultTicker_FontSelect.DataTextField = "Name";
            DefaultTicker_FontSelect.DataValueField = "Name";
            DefaultTicker_FontSelect.DataBind();
            DefaultTicker_FontSelect.Items.Insert(0, "Insert Font Tag");
            DefaultTicker_FontSelect.SelectedIndex = 0;
            DefaultTicker_FontSelect.Attributes.Add("onchange", "insertTag(-1, \"Font\");");
            DefaultTicker_FontSelect.Style.Add("max-width", "173px");

            DefaultTicker_FontColorSelect.DataSource = ColorList;
            DefaultTicker_FontColorSelect.DataTextField = "Name";
            DefaultTicker_FontColorSelect.DataValueField = "HexValue";
            DefaultTicker_FontColorSelect.DataBind();
            foreach (ListItem li in DefaultTicker_FontColorSelect.Items)
            {
                String tmpName = li.Text;
                String tmpHex = li.Value;
                li.Text = tmpName + " (#" + tmpHex + ")";
            }
            DefaultTicker_FontColorSelect.Items.Insert(0, "Insert Font Color Tag");
            DefaultTicker_FontColorSelect.SelectedIndex = 0;
            DefaultTicker_FontColorSelect.Attributes.Add("onchange", "insertTag(-1, \"Color\");");
            DefaultTicker_FontColorSelect.Style.Add("max-width", "173px");

            DefaultTicker_CustomColorBtn.OnClientClick = "insertTag(-1, \"CustomColor\"); return false;";

            DefaultTicker_ImageSelect.DataSource = ImageTagList;
            DefaultTicker_ImageSelect.DataTextField = "Name";
            DefaultTicker_ImageSelect.DataValueField = "ID";
            DefaultTicker_ImageSelect.DataBind();
            DefaultTicker_ImageSelect.Items.Insert(0, "Insert Image Tag");
            DefaultTicker_ImageSelect.SelectedIndex = 0;
            DefaultTicker_ImageSelect.Attributes.Add("onchange", "insertTag(-1, \"Image\");");
            DefaultTicker_ImageSelect.Style.Add("max-width", "173px");

            DefaultTicker_DataTagSelect.DataSource = DataTagList;
            DefaultTicker_DataTagSelect.DataTextField = "Name";
            DefaultTicker_DataTagSelect.DataValueField = "ID";
            DefaultTicker_DataTagSelect.DataBind();
            DefaultTicker_DataTagSelect.Items.Insert(0, "Insert Data Tag");
            DefaultTicker_DataTagSelect.SelectedIndex = 0;
            DefaultTicker_DataTagSelect.Attributes.Add("onchange", "insertTag(-1, \"Data\");");
            DefaultTicker_DataTagSelect.Style.Add("max-width", "173px");
        }

    }


    //Load the String Tag rule from datatable by given stringID
    protected void LoadTagRule(int stringID)
    {

        Magnolia.STRINGTAGVALUEDataTable stringValues = new STRINGTAGVALUETableAdapter().GetDataByID(stringID);
        int i = 0;

        Hidden_StringTagID.Value = stringID.ToString();

        RulePanel.Controls.Clear();
        foreach (Magnolia.STRINGTAGVALUERow strValue in stringValues.Rows)
        {
            bool pass = true;

            if (tmpDelRuleLists != null)
            {
                //check if the rule is been added into the delete list
                foreach (int tIndex in tmpDelRuleLists)
                {
                    if (i == tIndex)
                    {
                        pass = false;
                        break;
                    }
                }
            }

            if (pass)
                RenderTagValue(strValue.DataTagID, strValue.Comparator.Trim(), strValue.MatchValue.Trim(), strValue.ThenValue.Trim(), i);
            i++;
        }

        UpdatePlusButton();
    }

    protected void UpdatePlusButton()
    {
        //update the number of rule in the panel
        indexCounter = RulePanel.Controls.Count;

        for (int j = 0; j < emptyCounter; j++)
            PlusButton(j);

        if (indexCounter == 0 && emptyCounter <= 0)
        {
            PlusButton(0);
            emptyCounter++;
        }

        //update the number of the rules after pop the empty rule
        indexCounter = RulePanel.Controls.Count;
    }

    //Fill the Panel with Controler
    protected void RenderTagValue(int dataTagID, string compaText, string matchText, string thenValue, int counter)
    {
        Magnolia.DATATAGDataTable D_Tags = new DATATAGTableAdapter().GetData();
        DropDownList dataTagList = new DropDownList();
        DropDownList comparatorList = new DropDownList();
        TextBox TBox_Match = new TextBox();
        TextBox TBox_ThenValue = new TextBox();
        Button BtnPlus = new Button();
        Button BtnMinus = new Button();

        dataTagList.Enabled = enableButton;
        dataTagList.DataSource = D_Tags;
        dataTagList.DataTextField = "Name";
        dataTagList.DataValueField = "ID";
        dataTagList.DataBind();
        dataTagList.SelectedValue = dataTagID.ToString();

        comparatorList.Enabled = enableButton;
        comparatorList.Items.Add("=");
        comparatorList.Items.Add("!=");
        comparatorList.Items.Add(">");
        comparatorList.Items.Add(">=");
        comparatorList.Items.Add("<");
        comparatorList.Items.Add("<=");
        comparatorList.Items.FindByText(compaText).Selected = true;

        TBox_ThenValue.TextMode = TextBoxMode.MultiLine;
        TBox_ThenValue.Attributes.Add("class", "widthXL heightS");
        TBox_ThenValue.Style.Add("overflow", "visible");

        BtnPlus.Text = "+";
        BtnMinus.Text = "-";
        BtnPlus.Enabled = enableButton;
        BtnMinus.Enabled = enableButton;
        BtnPlus.Attributes.Add("onclick", "updateHiddenCheckBox();");
        //Assign the row with individual ID
        BtnMinus.Attributes.Add("onclick", "updateHiddenTextBox(" + counter + ");");

        TBox_Match.Text = matchText;
        TBox_ThenValue.Text = thenValue;
        TBox_Match.Enabled = enableButton;
        TBox_ThenValue.Enabled = enableButton;
        TBox_ThenValue.ID = "tickerEditorTextArea_" + Convert.ToString(counter);

        GenerateTag(BtnPlus, BtnMinus, dataTagList, comparatorList, TBox_Match, TBox_ThenValue);
    }

    //Generate the Html component and add it into the display panel
    protected void GenerateTag(Button BtnPlus, Button BtnMinus, DropDownList dataTagList, DropDownList comparatorList, TextBox TBox_Match, TextBox TBox_ThenValue)
    {
        HtmlGenericControl rows = new HtmlGenericControl("div");
        rows.Attributes.Add("class", "row");

        HtmlGenericControl ruleRow = new HtmlGenericControl("div");
        ruleRow.Attributes.Add("class", "row");

        HtmlGenericControl spaceS = new HtmlGenericControl("div");
        spaceS.Attributes.Add("class", "spacerS");

        HtmlGenericControl spaceS2 = new HtmlGenericControl("div");
        spaceS2.Attributes.Add("class", "spacerS");

        HtmlGenericControl spaceS3 = new HtmlGenericControl("div");
        spaceS3.Attributes.Add("class", "spacerS");

        HtmlGenericControl spaceL = new HtmlGenericControl("div");
        spaceL.Attributes.Add("class", "spacerL");

        HtmlGenericControl spaceL2 = new HtmlGenericControl("div");
        spaceL2.Attributes.Add("class", "spacerL");

        HtmlGenericControl spaceL3 = new HtmlGenericControl("div");
        spaceL3.Attributes.Add("class", "spacerL");

        HtmlGenericControl arrowR = new HtmlGenericControl("img");
        arrowR.Attributes.Add("alt", "right arrow");
        arrowR.Attributes.Add("src", "images/arrow_right.gif");
        arrowR.Attributes.Add("style", "float:left;");

        ruleRow.Controls.Add(BtnPlus);
        ruleRow.Controls.Add(spaceS);
        ruleRow.Controls.Add(BtnMinus);
        ruleRow.Controls.Add(spaceL);
        ruleRow.Controls.Add(dataTagList);
        ruleRow.Controls.Add(spaceL2);
        ruleRow.Controls.Add(comparatorList);
        ruleRow.Controls.Add(spaceL3);
        ruleRow.Controls.Add(TBox_Match);
        ruleRow.Controls.Add(spaceS2);
        ruleRow.Controls.Add(arrowR);
        ruleRow.Controls.Add(spaceS3);

        // add second row with ticker editor container and TBox_ThenValue
        HtmlGenericControl tickerEditorRow = new HtmlGenericControl("div");
        tickerEditorRow.Attributes.Add("class", "row");
        tickerEditorRow.Style.Add("margin-left", "100px");
        tickerEditorRow.Style.Add("background-color", "#ddd");
        tickerEditorRow.Style.Add("border", "1px solid #aaa");
        tickerEditorRow.Style.Add("padding", "5px");
        tickerEditorRow.Style.Add("width", "812px");

        HtmlGenericControl tickerContainer = new HtmlGenericControl("div");
        string[] TBoxSplit = TBox_ThenValue.ID.Split('_');
        int CurrentIndex = Convert.ToInt32(TBoxSplit[1]);
        tickerContainer.ID = "tickerEditorContainer_" + Convert.ToString(CurrentIndex);
        tickerContainer.Attributes.Add("class", "tickerEditor");

        // re-create ticker interface here
        DropDownList FontSelect = new DropDownList();
        //Magnolia.FONTDataTable FontList = new FONTTableAdapter().GetFonts();
        FontSelect.Enabled = enableButton;
        FontSelect.DataSource = FontList;
        FontSelect.DataTextField = "Name";
        FontSelect.DataValueField = "Name";
        FontSelect.DataBind();
        FontSelect.Items.Insert(0, "Insert Font Tag");
        FontSelect.SelectedIndex = 0;
        FontSelect.ID = "FontSelect_" + Convert.ToString(CurrentIndex);
        FontSelect.Attributes.Add("onchange", "insertTag(" + CurrentIndex + ", \"Font\");");
        FontSelect.Style.Add("max-width", "173px");

        HtmlGenericControl spacerM1 = new HtmlGenericControl("div");
        spacerM1.Attributes.Add("class", "spacerM");

        DropDownList ColorSelect = new DropDownList();
        //Magnolia.COLORFONTDataTable ColorList = new COLORFONTTableAdapter().GetColorFonts();
        ColorSelect.Enabled = enableButton;
        ColorSelect.DataSource = ColorList;
        ColorSelect.DataTextField = "Name";
        ColorSelect.DataValueField = "HexValue";
        ColorSelect.DataBind();
        foreach (ListItem li in ColorSelect.Items)
        {
            String tmpName = li.Text;
            String tmpHex = li.Value;
            li.Text = tmpName + " (#" + tmpHex + ")";
        }
        ColorSelect.Items.Insert(0, "Insert Font Color Tag");
        ColorSelect.SelectedIndex = 0;
        ColorSelect.ID = "FontColorSelect_" + Convert.ToString(CurrentIndex);
        ColorSelect.Attributes.Add("onchange", "insertTag(" + CurrentIndex + ", \"Color\");");
        ColorSelect.Style.Add("max-width", "173px");

        HtmlGenericControl spacerM2 = new HtmlGenericControl("div");
        spacerM2.Attributes.Add("class", "spacerM");

        Button CustomColorBtn = new Button();
        CustomColorBtn.Text = "Custom Font Color";
        CustomColorBtn.Enabled = enableButton;
        CustomColorBtn.ID = "CustomColorBtn_" + Convert.ToString(CurrentIndex);
        CustomColorBtn.OnClientClick = "insertTag(" + CurrentIndex + ", \"CustomColor\"); return false;";

        HtmlGenericControl spacerM3 = new HtmlGenericControl("div");
        spacerM3.Attributes.Add("class", "spacerM");

        DropDownList ImageSelect = new DropDownList();
        //Magnolia.IMAGETAGDataTable ImageTagList = new IMAGETAGTableAdapter().GetData();
        ImageSelect.Enabled = enableButton;
        ImageSelect.DataSource = ImageTagList;
        ImageSelect.DataTextField = "Name";
        ImageSelect.DataValueField = "ID";
        ImageSelect.DataBind();
        ImageSelect.Items.Insert(0,"Insert Image Tag");
        ImageSelect.SelectedIndex = 0;
        ImageSelect.ID = "ImageSelect_" + Convert.ToString(CurrentIndex);
        ImageSelect.Attributes.Add("onchange", "insertTag(" + CurrentIndex + ", \"Image\");");
        ImageSelect.Style.Add("max-width", "173px");

        HtmlGenericControl spacerM4 = new HtmlGenericControl("div");
        spacerM4.Attributes.Add("class", "spacerM");

        DropDownList DataTagSelect = new DropDownList();
        //Magnolia.DATATAGDataTable DataTagList = new DATATAGTableAdapter().GetDataTagsEnabledAndOrderedByName();
        DataTagSelect.Enabled = enableButton;
        DataTagSelect.DataSource = DataTagList;
        DataTagSelect.DataTextField = "Name";
        DataTagSelect.DataValueField = "ID";
        DataTagSelect.DataBind();
        DataTagSelect.Items.Insert(0, "Insert Data Tag");
        DataTagSelect.SelectedIndex = 0;
        DataTagSelect.ID = "DataTagSelect_" + Convert.ToString(CurrentIndex);
        DataTagSelect.Attributes.Add("onchange", "insertTag(" + CurrentIndex + ", \"Data\");");
        DataTagSelect.Style.Add("max-width", "173px");

        tickerContainer.Controls.Add(FontSelect);
        tickerContainer.Controls.Add(spacerM1);
        tickerContainer.Controls.Add(ColorSelect);
        tickerContainer.Controls.Add(spacerM2);
        tickerContainer.Controls.Add(CustomColorBtn);
        tickerContainer.Controls.Add(spacerM3);
        tickerContainer.Controls.Add(ImageSelect);
        tickerContainer.Controls.Add(spacerM4);
        tickerContainer.Controls.Add(DataTagSelect);
        tickerContainer.Controls.Add(TBox_ThenValue);
        
        // now add final row containing ticker editor container
        tickerEditorRow.Controls.Add(tickerContainer);

        rows.Controls.Add(ruleRow);
        rows.Controls.Add(tickerEditorRow);
        RulePanel.Controls.Add(rows);
    }

    //Load the list of string tag with give tag Index
    protected void LoadList(int tagIndex)
    {
        ListBox_StringTags.DataSource = stringTags;
        ListBox_StringTags.DataTextField = "Name";
        ListBox_StringTags.DataValueField = "ID";
        ListBox_StringTags.DataBind();

        if (stringTags.Rows.Count > 0)
        {
            if (tagIndex > 0)
            {
                ListBox_StringTags.SelectedValue = tagIndex.ToString();
                Lbl_PageHeader.Text = "StringTag: " + ListBox_StringTags.SelectedItem.Text;
            }
            else
            {
                ListBox_StringTags.SelectedIndex = 0;
                Lbl_PageHeader.Text = "StringTag: " + ListBox_StringTags.SelectedItem.Text;
                tagIndex = 1;
            }
            LoadForm(tagIndex);
        }
        else
        {
            Lbl_PageHeader.Text = "StringTags";
            Lbl_EditorAlerts.Visible = false;
        }
        LoadTagRule(tagIndex);
        Btn_CancelChanges.Enabled = false;
    }

    //Overload the function with customer bulid Message
    protected void LoadList(int tagIndex, string message)
    {
        ListBox_StringTags.DataSource = stringTags;
        ListBox_StringTags.DataTextField = "Name";
        ListBox_StringTags.DataValueField = "ID";
        ListBox_StringTags.DataBind();

        if (stringTags.Rows.Count > 0)
        {
            ListBox_StringTags.SelectedValue = tagIndex.ToString();
            Lbl_PageHeader.Text = message;
            LoadForm(tagIndex);
        }
        else
        {
            Lbl_PageHeader.Text = "StringTags";
            Lbl_EditorAlerts.Visible = false;
        }
        LoadTagRule(tagIndex);
        Btn_CancelChanges.Enabled = false;
    }

    //Fill the form with the information of Selected StringTag
    protected void LoadForm(int tagID)
    {
        Hidden_ID.Value = tagID.ToString();
        Magnolia.STRINGTAGRow tagRow = stringTags.FindByID(tagID);
        TBox_Name.Text = tagRow.Name;
        TBox_LastValue.Text = tagRow.LastValue;
        Text_LastSuccessParsed.Text = tagRow.LastSuccessfulCheck.ToString();
        Text_LastParsed.Text = tagRow.LastChecked.ToString();
        Text_DefaultStringValue.Text = tagRow.DefaultValue;
    }


    //Event when list selection change
    protected void ListBox_StringTags_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ListBox_StringTags.SelectedValue != "")
        {
            Lbl_TestAlerts.Visible = false;
            emptyCounter = 0;
            Hidden_StringTagID.Value = ListBox_StringTags.SelectedValue;
            LoadList(Convert.ToInt32(ListBox_StringTags.SelectedValue));
            Lbl_EditorAlerts.Visible = false;

        }
    }

    //To generate the empty string tag rule
    protected void PlusButton(int bIndex)
    {
        Magnolia.DATATAGDataTable D_Tags = new DATATAGTableAdapter().GetData();
        DropDownList dataTagList = new DropDownList();
        DropDownList comparatorList = new DropDownList();
        TextBox TBox_Match = new TextBox();
        TextBox TBox_ThenValue = new TextBox();
        Button BtnPlus = new Button();
        Button BtnMinus = new Button();

        dataTagList.Enabled = true;
        dataTagList.DataSource = D_Tags;
        dataTagList.DataTextField = "Name";
        dataTagList.DataValueField = "ID";
        dataTagList.DataBind();

        comparatorList.Enabled = true;
        comparatorList.Items.Add("=");
        comparatorList.Items.Add("!=");
        comparatorList.Items.Add(">");
        comparatorList.Items.Add(">=");
        comparatorList.Items.Add("<");
        comparatorList.Items.Add("<=");

        TBox_ThenValue.TextMode = TextBoxMode.MultiLine;
        TBox_ThenValue.Attributes.Add("class", "widthXL heightS");
        TBox_ThenValue.Style.Add("overflow", "visible");

        BtnPlus.Text = "+";
        BtnMinus.Text = "-";
        BtnPlus.Enabled = enableButton;
        BtnMinus.Enabled = enableButton;
        if (indexCounter == 0 && emptyCounter <= 1)
            BtnMinus.Enabled = false;
        BtnPlus.Attributes.Add("onclick", "updateHiddenCheckBox();");
        //Random randNo = new Random();randNo.Next(50,100)
        int position = 90 + bIndex;
        BtnMinus.Attributes.Add("onclick", "updateHiddenTextBox(" + position + ");");

        TBox_Match.Enabled = enableButton;
        TBox_ThenValue.Enabled = enableButton;
        TBox_ThenValue.ID = "tickerEditorTextArea_" + Convert.ToString(position);

        GenerateTag(BtnPlus, BtnMinus, dataTagList, comparatorList, TBox_Match, TBox_ThenValue);
    }

    //Diable the String tag list
    protected void DisableList()
    {
        Btn_Refresh.Enabled = false;
        ListBox_StringTags.Enabled = false;
        ListBox_StringTags.BackColor = System.Drawing.Color.LightGray;
        Check_Disabled.Enabled = false;
        Btn_Disable.Enabled = false;
        Btn_Enable.Enabled = false;
    }

    //Enable the String tag list
    protected void EnableList()
    {
        Btn_Refresh.Enabled = true;
        ListBox_StringTags.Enabled = true;
        ListBox_StringTags.BackColor = System.Drawing.Color.White;
        Check_Disabled.Enabled = true;
        Btn_Disable.Enabled = true;
        Btn_Enable.Enabled = true;

    }

    //Reassign the Control's availibility
    private void FieldEdit()
    {
        Btn_Save.Enabled = enableButton;
        Btn_CancelChanges.Enabled = enableButton;
        TBox_Name.Enabled = enableButton;

        // Enable ticker editor fields
        DefaultTicker_FontSelect.Enabled = enableButton;
        DefaultTicker_FontColorSelect.Enabled = enableButton;
        DefaultTicker_CustomColorBtn.Enabled = enableButton;
        DefaultTicker_ImageSelect.Enabled = enableButton;
        DefaultTicker_DataTagSelect.Enabled = enableButton;
        Text_DefaultStringValue.Enabled = enableButton;
    }

    //The hiddent Check Box for Plus Button event
    protected void hidden_CheckBox_CheckedChanged(object sender, EventArgs e)
    {
        RulePanel.Controls.Clear();
        emptyCounter++;
        //LoadTagRule(Convert.ToInt32(Hidden_StringTagID.Value));
        TempMemory(1);
        hidden_TextBox.Text = "-1";
        plusRule = true;
        minusRule = false;
    }

    protected void TempMemory(int buttonIndex)
    {
        string tmpSaveString = hidden_ContentSave.Text;
        string[] result = tmpSaveString.Split('?');

        int j = 0;
        int i;
        for (i = 0; i < indexCounter; i++)
        {
            if (j >= result.Length - 1)
                break;
            int tagID = Convert.ToInt32(result[j++]);
            string compaText = result[j++];
            string matchText = result[j++];
            string thenValue = result[j++];
            if (thenValue == "")
                break;
            if (i != Convert.ToInt32(hidden_TextBox.Text))
                RenderTagValue(tagID, compaText, matchText, thenValue, i);
        }
        if (indexCounter == i && buttonIndex == 1)
        {
            emptyCounter = 1;
        }
        else if (buttonIndex == 1)
        {
            emptyCounter = indexCounter - i + 1;
        }
        else if (buttonIndex == 2 && minusRule)
            emptyCounter = indexCounter - i;

        if (buttonIndex == 3)
            emptyCounter = 0;
        for (i = 0; i < emptyCounter; i++)
        {
            PlusButton(i);
        }

        indexCounter = RulePanel.Controls.Count;
    }

    //The hiddent TextBox for the Minus Button Event
    protected void hidden_TextBox_TextChanged(object sender, EventArgs e)
    {
        if (plusRule)
        {
            plusRule = false;
            minusRule = true;
        }
        else
        {
            minusRule = false;
        }
        DeleteTag();
    }

    protected void DeleteTag()
    {
        if (Convert.ToInt32(hidden_TextBox.Text) >= 90)
        {
            emptyCounter--;
        }
        //tmpDelRuleLists.Add(Convert.ToInt32(hidden_TextBox.Text));
        //LoadTagRule(Convert.ToInt32(Hidden_StringTagID.Value));
        TempMemory(2);
        hidden_TextBox.Text = "-1";
    }

    //Enable the Tag editing Event
    protected void Btn_EditTag_Click(object sender, EventArgs e)
    {
        Lbl_TestAlerts.Visible = false;
        enableButton = true;
        DisableList();
        FieldEdit();
        LoadTagRule(Convert.ToInt32(Hidden_StringTagID.Value));
    }

    //Cancel the Editing/Saving
    protected void Btn_CancelChanges_Click(object sender, EventArgs e)
    {
        Resume();
    }

    //Resume the page 
    protected void Resume()
    {
        Lbl_EditorAlerts.Visible = false;
        Lbl_TestAlerts.Visible = false;
        emptyCounter = 0;
        enableButton = false;
        Btn_EditTag.Enabled = true;
        tmpDelRuleLists.Clear();
        EnableList();
        FieldEdit();
        int stringID = Convert.ToInt32(Hidden_StringTagID.Value);
        tagsAdapter.Fill(stringTags);
        LoadList(stringID);

        if (stringID == 0)
            LoadTagRule(1);
        else
            LoadTagRule(stringID);
    }

    //Save string tag event 
    protected void Btn_Save_Click(object sender, EventArgs e)
    {
        int stringTagID;
        stringTagID = Convert.ToInt32(Hidden_StringTagID.Value);

        bool passInput = ValidateInput(stringTagID);

        if (!passInput)
        {
            LoadTagRule(Convert.ToInt32((Hidden_StringTagID.Value)));
            return;
        }

        STRINGTAGTableAdapter strTagAdapter = new STRINGTAGTableAdapter();
        STRINGTAGVALUETableAdapter strTagValueAdapter = new STRINGTAGVALUETableAdapter();
        tagsAdapter.Fill(stringTags);

        
        string saveString;


        //Save the regular field on the table stringtag
        if (Hidden_StringTagID.Value != "0")
        {
            Magnolia.STRINGTAGRow strRow = stringTags.FindByID(stringTagID);
            strRow.Name = TBox_Name.Text.Trim();
            strRow.DefaultValue = Text_DefaultStringValue.Text.Trim();
        }
        else
        {
            Magnolia.STRINGTAGRow newStrRow = stringTags.NewSTRINGTAGRow();
            newStrRow.Name = TBox_Name.Text.Trim();
            newStrRow.DefaultValue = Text_DefaultStringValue.Text.Trim();
            newStrRow.LastValue = "none";
            newStrRow.LastChecked = Convert.ToDateTime("01/01/1900");
            newStrRow.LastSuccessfulCheck = Convert.ToDateTime("01/01/1900");
            newStrRow.InUseNN = true;
            stringTags.Rows.Add(newStrRow);
            stringTagID = stringTags.Rows.Count;
        }
        strTagAdapter.Update(stringTags);

        strTagValueAdapter.DeleteAll(stringTagID);

        //save the tag rule on the string tag value table
        Magnolia.STRINGTAGVALUEDataTable strValueTable = new STRINGTAGVALUETableAdapter().GetData();

        saveString = hidden_ContentSave.Text;
        string[] result = saveString.Split('?');
        int j = 0;
        for (int i = 1; i <= indexCounter; i++)
        {
            Magnolia.STRINGTAGVALUERow newStrValueRow = strValueTable.NewSTRINGTAGVALUERow();
            newStrValueRow.StringTagID = stringTagID;
            newStrValueRow.Index = i;

            newStrValueRow.DataTagID = Convert.ToInt32(result[j++]);
            newStrValueRow.Comparator = result[j++];
            newStrValueRow.MatchValue = result[j++];
            newStrValueRow.ThenValue = result[j++];
            if (newStrValueRow.ThenValue == "")
                break;
            strValueTable.Rows.Add(newStrValueRow);
        }

        Hidden_StringTagID.Value = stringTagID.ToString();

        strTagValueAdapter.Update(strValueTable);
        Resume();
    }

    //Check if the user give right input 
    public bool ValidateInput(int stringTagID)
    {
        ArrayList errorList = new ArrayList();


        if (TBox_Name.Text.Trim() == "")
            errorList.Add("&#149; String tag name is a required field");
        else
        {
            //string command = "Select ID from Stringtag where Name ='" + TBox_Name.Text + "'";
            //int ID = Convert.ToInt32(getDataObject(command));
            //if (ID != 0 && stringTagID!= ID)
            string uniqueNameErr = ValidateUniqueInput(TBox_Name.Text);
            if (uniqueNameErr.Length > 0)
                errorList.Add(uniqueNameErr);
        }

        if (Text_DefaultStringValue.Text.Trim() == "")
            errorList.Add("&#149; String tag default value is a required field");
        if (errorList.Count != 0)
        {
            Lbl_EditorAlerts.Text = "";
            foreach (string msg in errorList)
                Lbl_EditorAlerts.Text += msg + "<BR>";

            Lbl_EditorAlerts.Visible = true;
            return false;
        }
        return true;
    }
    public string ValidateUniqueInput(string tagName)
    {
        int stringTagID;
        stringTagID = Convert.ToInt32(Hidden_StringTagID.Value);
        string errMsg = "";

        // query to get a list of items
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SuperSignConnectionString"].ConnectionString);
        //SqlDataReader reader = null;
        try
        {
            conn.Open();

            String sProc = "sproc_WEB_DoesTagNameExist";

            SqlCommand cmd = new SqlCommand(sProc, conn);
            cmd.CommandType = CommandType.StoredProcedure;

            // set paramter
            DbParameter param = cmd.CreateParameter();
            param.ParameterName = "@Name";
            param.Value = Convert.ToString(tagName.Trim());
            param.DbType = DbType.String;
            cmd.Parameters.Add(param);

            DbDataReader reader = cmd.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Load(reader);
            reader.Close();

            int returnedID = Convert.ToInt32(dt.Rows[0].ItemArray[0]);

            if ((returnedID != 0 && returnedID != stringTagID)
                || (returnedID != 0 && Convert.ToInt32(dt.Rows[0].ItemArray[1]) != 22))
            {
                int returnedLevel = Convert.ToInt32(dt.Rows[0].ItemArray[1]);
                if (returnedLevel == 21)
                    errMsg = "&#149; This tag name already exists as a data tag, please use a different tag name";
                else if (returnedLevel == 22)
                    errMsg = "&#149; This tag name already exists as a string tag, please use a different tag name";
                else if (returnedLevel == 23)
                    errMsg = "&#149; This tag name already exists as an image tag, please use a different tag name";
            }
        }
        catch (Exception ex)
        {
            String err = ex.Message;
        }
        finally
        {
            conn.Close();
        }

        return errMsg;
    }
    //Create new Tag event
    protected void Btn_NewTag_Click1(object sender, EventArgs e)
    {
        NewTagPage();
    }

    //Create new Tag
    protected void NewTagPage()
    {
        Hidden_StringTagID.Value = Convert.ToString(0);
        ListBox_StringTags.SelectedIndex = -1;
        Btn_EditTag.Enabled = false;
        enableButton = true;
        FieldEdit();
        ClearForm();
        DisableList();
        LoadTagRule(0);
    }

    //Clear the form
    protected void ClearForm()
    {
        Hidden_StringTagID.Value = "0";
        TBox_Name.Text = "";
        Text_DefaultStringValue.Text = "";
        TBox_LastValue.Text = "none";
        Text_LastParsed.Text = "none";
        Text_LastSuccessParsed.Text = "none";
    }

    //Enable the tag
    private void AbleTags(bool decision)
    {
        int stringTagID = Convert.ToInt32(Hidden_ID.Value);
        Magnolia.STRINGTAGRow tagRow = stringTags.FindByID(stringTagID);
        tagRow.InUseNN = decision;
        tagsAdapter.Update(tagRow);

        if (decision)
            LoadList(stringTagID, "String Tag: \"" + tagRow.Name + "\" successfully Enabled");
        else
            Lbl_PageHeader.Text = "String Tag: \"" + tagRow.Name + "\" successfully Disabled";
    }

    //Check if the disable check is trigger 
    protected void Check_Disabled_CheckedChanged(object sender, EventArgs e)
    {
        ReloadList();
    }

    //Reload the List 
    private void ReloadList()
    {
        if (Check_Disabled.Checked)
            tagsAdapter.FillByInUseNN(stringTags);
        else
            tagsAdapter.Fill(stringTags);

        LoadList(1);
    }

    //Diable button Click
    protected void Btn_Disable_Click(object sender, EventArgs e)
    {
        AbleTags(false);
    }

    //Enable Button Event trigger
    protected void Btn_Enable_Click(object sender, EventArgs e)
    {
        AbleTags(true);
    }

    //Refresh the stringtag list
    protected void Btn_Refresh_Click(object sender, EventArgs e)
    {
        ReloadList();
    }

    //Test the Current String tag rules
    protected void Btn_Test_Click(object sender, EventArgs e)
    {
        string command;
        string XMLstring = "";

        TempMemory(3);

        //Generate teh XML string to pass to the stored procedure 
        XMLstring += "<StringTagTest>";
        XMLstring += "<StringTag Name=\"" + TBox_Name.Text + "\">";
        XMLstring += "<DefaultValue>";
        XMLstring += "<![CDATA[" + Text_DefaultStringValue.Text + "]]>";
        XMLstring += "</DefaultValue>";

        string tmpSaveString = hidden_ContentSave.Text;
        string[] result = tmpSaveString.Split('?');
        int j = 0;

        for (int i = 0; i < indexCounter; i++)
        {
            if (j >= result.Length - 1)
                break;
            XMLstring += "<Rule DataTagID=\"" + result[j++];
            string exChange = result[j++];
            if (exChange == "<")
                exChange = "&lt;";
            else if (exChange == "<=")
                exChange = "&lt;=";
            XMLstring += "\" Comparator=\"" + exChange + "\" MatchValue=\"" + result[j++] + "\">";
            XMLstring += "<![CDATA[" + result[j++] + "]]>";
            XMLstring += "</Rule>";
        }
        XMLstring += "</StringTag>";
        XMLstring += "</StringTagTest>";

        command = "sproc_WEB_TestStringTag @Rules='" + XMLstring + "'";
        string testResult = getDataObject(command).ToString();
        Lbl_TestAlerts.Text = testResult;
        Lbl_TestAlerts.Visible = true;
    }

    //Connect to the database and retreve the return value
    public object getDataObject(string selectSQL)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SuperSignConnectionString"].ConnectionString);
        SqlCommand cmd = new SqlCommand(selectSQL, con);
        SqlDataReader reader = null;
        object ob = 0;

        try
        {
            con.Open();
            reader = cmd.ExecuteReader();
            reader.Read();
            ob = reader[0];//Only read ONE data in the first of list
            reader.Close();

        }
        catch (Exception err)
        {
            //displayError("Error occur while connect to DataBase via DataReader, Check Connection : \n" + err);
        }
        finally
        {
            con.Close();
        }
        return ob;

    }
}